from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from six_it.models import User


class UserRegiestSerizlizers(serializers.ModelSerializer):
    sms_code = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True, required=False)
    avatar = serializers.CharField(read_only=True, required=False)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile', 'sms_code', 'token', 'avatar']
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        sms_code = attrs.pop('sms_code')
        redis_conn = get_redis_connection('verify_code')
        code = redis_conn.get('sms_%s' % mobile)
        if not code:
            raise ValueError('短信验证码过期')
        if sms_code != code.decode():
            raise ValueError('验证码错误')
        redis_conn.delete('sms_%s' % mobile)
        return attrs

    def create(self, validated_data):
        user = User.objects.create_user(nickname=validated_data.get('username'),**validated_data)
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token
        return user
